package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.model.bean.FlashSaleGoodsListResponse
import com.gexiaobao.pigeon.app.model.bean.SaleTimesListResponse
import com.gexiaobao.pigeon.app.network.ListDataUiState
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentFlashSaleGoodsBinding
import com.gexiaobao.pigeon.ui.adapter.FlashSaleGoodsAdapter
import com.gexiaobao.pigeon.ui.adapter.FlashSaleTimesAdapter
import com.gexiaobao.pigeon.ui.adapter.FlashSaleTimesAdapter2
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.kingja.loadsir.core.LoadService
import com.loan.golden.cash.money.interval.Interval
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.util.concurrent.TimeUnit


/**
 * @Author      : hxw
 * @Date        : 2024/1/26 15:18
 * @Describe    : 限时抢购
 */
class FlashSaleGoodsFragment : BaseFragment<MallViewModel, FragmentFlashSaleGoodsBinding>() {

    private lateinit var timesAdapter: FlashSaleTimesAdapter
    private lateinit var timesAdapter2: FlashSaleTimesAdapter2
    private val goodsAdapter: FlashSaleGoodsAdapter by lazy { FlashSaleGoodsAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private var timesId: Int = 0
    private var selectedIndex: Int = 0
    private lateinit var interval: Interval // 轮询器
    private var mIsRefresh = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun onResume() {
        super.onResume()
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.tvWhiteTitle.text = getString(R.string.flash_sale)
        timesId = requireArguments().getInt("timesId")
        /** 初始化产品介绍recycleView */
        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), goodsAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 5f)))
            it.initFooter {
                mViewModel.getSaleListBySaleTimeId(false, timesId)
            }
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            /** 点击重试时触发的操作 */
            onRefresh(true)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh(true)
        }

        goodsAdapter.addChildClickViewIds(R.id.tvItemFlashSaleGoodsBuyNow)
        goodsAdapter.setOnItemChildClickListener { adapter, view, position ->
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", goodsAdapter.data[position].goodsId.toString())
            })
        }
    }

    private fun onRefresh(isRefresh: Boolean) {
        mIsRefresh = isRefresh
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.getSaleListBySaleTimeId(isRefresh, timesId)
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoading(getString(R.string.loading))
        mViewModel.getSaleTimeList()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取抢购场次商品详情 */
        mViewModel.saleListDetailResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            loadListData(it, goodsAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
            refreshDataState(it)
        }
        /** 获取场次列表 */
        mViewModel.saleTimeListResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isEmpty() || it.list.size == 0) {
                return@observe
            }
            onRefresh(true)
            initFlashSaleAdapter(it)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun refreshDataState(it: ListDataUiState<FlashSaleGoodsListResponse.ListBean>?) {
        if (!mIsRefresh) return
        if (it != null) {
            val state = it.state
            if (state == 3) {
                mDatabind.llFlashSaleType.isVisible = false
                mDatabind.llFlashSaleTypeUnStart.isVisible = false
                mDatabind.llEndOfActivity.isVisible = true
                if (::interval.isInitialized)
                    interval.cancel()
                return
            }

            when (state) {//1-未开始2-进行中3-已结束
                1 -> {
                    mDatabind.llFlashSaleType.isVisible = false
                    mDatabind.llFlashSaleTypeUnStart.isVisible = true
                    mDatabind.llEndOfActivity.isVisible = false
                    mDatabind.tvFlashSaleTimeUnStart.text = getString(R.string.start_time) + { it.startTime }
                    if (::interval.isInitialized)
                        interval.cancel()
                    return
                }

                2 -> {
                    mDatabind.llFlashSaleType.isVisible = true
                    mDatabind.llFlashSaleTypeUnStart.isVisible = false
                    mDatabind.llEndOfActivity.isVisible = false
                    interval = Interval(0, 1, TimeUnit.SECONDS, it.countDown).life(this) // 自定义计数器个数的轮询器, 当[start]]比[end]值大, 且end不等于-1时, 即为倒计时
                    interval.subscribe {
                        mDatabind.tvFlashSaleTime.text = getString(R.string.end_Distance) + DatetimeUtil.formatDateTime2(it)
                    }.finish {
                        nav().navigateUp()
                    }.start()
                    return
                }

                else -> {
                    mDatabind.llFlashSaleType.isVisible = false
                    mDatabind.llFlashSaleTypeUnStart.isVisible = false
                    mDatabind.llEndOfActivity.isVisible = false
                    if (::interval.isInitialized)
                        interval.cancel()
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n", "SuspiciousIndentation")
    private fun initFlashSaleAdapter(it: SaleTimesListResponse?) {
        if (it != null) {
            it.list.forEachIndexed { index, listBean ->
                if (timesId == listBean.id) {
                    selectedIndex = index
                }
            }

            timesAdapter = FlashSaleTimesAdapter(ArrayList(), this.selectedIndex)
            timesAdapter2 = FlashSaleTimesAdapter2(ArrayList(), this.selectedIndex)
            if (it.list.size > 3) {
                mDatabind.recyclerviewTimes.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                mDatabind.recyclerviewTimes.adapter = timesAdapter
                timesAdapter.setList(it.list)
                timesAdapter.notifyDataSetChanged()
            } else {
                mDatabind.recyclerviewTimes.init(GridLayoutManager(context, it.list.size), timesAdapter2)
                    .addItemDecoration(
                        SpaceItemDecoration(0, 0)
                    )
                timesAdapter2.setList(it.list)
                timesAdapter2.notifyDataSetChanged()
            }
        }

        timesAdapter.setOnTimesClickListener(object : FlashSaleTimesAdapter.OnTimesItemClickListener {
            override fun onItemClick(id: Int) {
                timesId = id
                onRefresh(true)
            }
        })
        timesAdapter2.setOnTimesClickListener(object : FlashSaleTimesAdapter2.OnTimesItemClickListener {
            override fun onItemClick(id: Int) {
                timesId = id
                onRefresh(true)
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    nav().navigateUp()
                }
            }
        }
    }

    override fun onStop() {
        super.onStop()
        if (::interval.isInitialized) {
            interval.cancel()
        }
    }
}